package com.andnnl.map;

import cn.hutool.core.util.RandomUtil;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by chenss on 2022/4/22.
 */
public class ComputeIfAbsentTest {

    static Map<String, String> userMap = new ConcurrentHashMap<>();//用户map

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
//        test3();
        getSameHashCodeList();
    }

    private static void getSameHashCodeList() {
        for (int i = 0; i < 1000000; i++) {
//            String key= RandomUtil.randomString(10);
            String key= ""+i;
//            System.out.println(key.hashCode() +"\t" +key);
            System.out.println(key.hashCode());
//            ;
        }
    }

    private static void test3() throws InterruptedException {
        long t1 = System.currentTimeMillis();
        int total = 1000000;
        Random r=new Random();
        CountDownLatch count=new CountDownLatch(total);
        ExecutorService executorService = Executors.newFixedThreadPool(100000);
        for (int i = 0; i < total; i++) {
            String key = "asdf_"+ r.nextInt(100);
//            String key = "asdf";
            executorService.submit(() -> {
                userMap.computeIfAbsent(key,k->{
//                    System.out.println("init...");
                    return "aaaa";
                });
                count.countDown();
            });
        }
        count.await();
        long t2 = System.currentTimeMillis();
        System.out.println("finish "+(t2-t1));
        System.out.println(userMap.size());
    }

    private static void test2() {
        String key = "asdf2";
        String rs = get2(key);
        String rs2 = get2(key);
        System.out.println(rs);
        System.out.println(rs2);
        System.out.println(userMap.get(key));
    }

    private static String get2(String key) {
        String b = userMap.get(key);
        if(b == null)
            userMap.putIfAbsent(key, build());
        return userMap.get(key);
    }

    private static void test1() {
        String key = "asdf1";
        String rs = get1(key);
        String rs2 = get1(key);
        String rs3 = get1(key);
        System.out.println(rs);
        System.out.println(rs2);
        System.out.println(rs3);
        System.out.println(userMap.get(key));
    }
    private static String get1(String key) {
        return userMap.putIfAbsent(key, build());
    }
    private static String build() {
        System.out.println("build");
        return new String("sssssss");
    }
}
